<?php

class CisController extends AppController
{
    # Controller Name to be used
    var $name = 'Cis';

    # Models to be used
    var $uses = array(
        'CisUser','ServiceCharge'
    );

    # set the layout to use
    var $layout = 'cis_layout';

    function __validateLoginStatus()
    {
        if ($this->params['action'] != 'login' && $this->params['action'] != 'logout') {
            if ($this->Session->check('loginData') == false) {
                $this->redirect(array('action' => 'login?ref=' . $this->params['action']));
            } else {
                $auth_user = $this->Session->read('loginData');
                //check if the user has not done multiple login
                $db_login_session = $this->getLoginSession($auth_user['id']);
                $login_session = $auth_user['login_session'];
                if ($db_login_session != $login_session) {
                    $this->Session->setFlash('Your session has expired!');
                    $this->redirect(array('action' => 'logout'));
                }
                //authorize the user, if the user is not authorized to view this page then redirect them to their session
                //$auth_user = $this->Session->read('loginData');
                if ($auth_user['user_type'] != 'cis_user') {
                    if ($auth_user['user_type'] == 'student_user') {
                        $this->redirect(array('controller' => 'Student', 'action' => 'index'));
                    } elseif ($auth_user['user_type'] == 'bank_user') {
                        $this->redirect(array('controller' => 'Bank', 'action' => 'index'));
                    } else {
                        $this->redirect(array('action' => 'logout'));
                    }
                } else { // For non Admin Staff only
                   /* $user_level = $auth_user['user_level'];
                    if ($user_level == 'Admin') {
                        $this->redirect(array('controller' => 'CisAdmin', 'action' => 'index'));
                    }*/
                }
            }
        }
    }

    private function getLoginSession($user_id)
    {
        $data = $this->CisUser->find('first', array(
            'conditions' => array('id' => $user_id),
            'recursive' => -1
        ));
        return $data['CisUser']['login_session'];
    }

    function  beforeFilter()
    {
        parent::beforeFilter();
        $this->__validateLoginStatus();
    }


    public function login()
    {
        if ($this->request->is('post')) {
            $logme  = $this->request->data['CisUser'];
            $logme = $this->CisUser->sanitize($logme);
            $result = $this->CisUser->login($logme['username'], $logme['password']);
            //exit;
            if ($result['status']) {
                //start a new session for this user
                $loginData = $this->createLoginSession($result['data']['CisUser']);
                //write data to session
                $this->Session->write('loginData', $loginData);

                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash($result['msg']);
            }
        }

        $this->layout = 'login_layout';
    }

    private function createLoginSession($data)
    {
        $login_session = $this->randomString(50);
        $data['login_session'] = $login_session;
        $this->CisUser->save(array(
            'id' => $data['id'],
            'login_session' => $login_session
        ));
        return $data;
    }

    public function logout()
    {
        $this->Session->delete('loginData');
        $this->Session->destroy();
        $this->redirect(array('action' => 'login'));
    }


    function editprofile()
    {
        if ($this->request->is('post')) {
            $error = false;
            $auth_user = $this->Session->read('loginData');

            if ($this->request->data['CisUser']['password']) {
                //echo 'yes';
                $this->request->data['CisUser']['password'] = md5(trim($this->request->data['CisUser']['password']));
            } else {
                $auth_user = $this->Session->read('loginData');
                $this->request->data['CisUser']['password'] = $auth_user['password'];
            }

            if ($error) {
                $this->Session->write('process_error', 'yes');
            } else {
                $result = $this->CisUser->save($this->request->data);

                if ($result) {
                    //write data to session
                    $user = $this->CisUser->getUserById($this->request->data['CisUser']['id']);
                    $this->Session->write('loginData', $user['CisUser']);
                    $this->Session->setFlash('Your profile info has been updated !');
                    $this->Session->write('process_error', 'no');
                    //$msg ="Dear ".$auth_user['fname']." your account profile has been updated.";
                    //$msg = 'Your have successfully paid GHS'.$total_paying.'. as fees for '.$this->current_academic_year.' academic year.';

                    /* $fon_number = $this->request->data['StudentUser']['cellphone'];
                     $this->Message->sendSMS($msg, $fon_number);*/
                } else {
                    $this->Session->setFlash('Sorry, your profile info could not be updated');
                    $this->Session->write('process_error', 'yes');
                }
            }

            $this->redirect(array('action' => 'editprofile'));
        }
        $controller = $this;
        $this->set(compact('controller'));
    }


    # Controller actions
    /**
     * @name index
     * @param void
     * @return Array of data.
     * @access public
     */
    function index()
    {
        $auth_user = $this->Session->read('loginData');
        $user_level = $auth_user['user_level'];
        if ($user_level == 'Admin') {
            $this->redirect(array('controller' => 'CisAdmin', 'action' => 'index'));
        }
        else{
            $this->redirect(array('controller' => 'Cis', 'action' => 'invoice'));
        }
    }


    function invoice(){
        $auth_user = $this->Session->read('loginData');

        $start_dt = $default_start_dt = date('Y-m-01');
        $end_dt = $default_end_dt = date('Y-m-t');
        $report_type = 'details';
        if ($this->request->is('post')) {
            $p_data = $this->request['data']['Query'];
            $p_data = $this->CisUser->sanitize($p_data);
            $start_dt = $default_start_dt = $p_data['start_dt'];
            $end_dt = $default_end_dt = $p_data['end_dt'];
            $report_type = $p_data['report_type'];
        }
        $data_table = $this->ServiceCharge->getCisBills($start_dt,$end_dt,$report_type);

        $report_type_opt = array('details' => 'Details','consolidated' => 'Consolidated');
        $controller = $this;

        $this->set(compact('page_title', 'report_type_opt', 'report_type','default_start_dt', 'default_end_dt', 'data_table','controller'));

    }


}
